<?php
Class error {
	
	const TYPE_NOTICE = 1;
	const TYPE_WARNING = 2;
	const TYPE_FATAL = 3;
	const TYPE_ACL = 4;
	
	/**
	 * Error handler
	 * see: http://codingforums.com/showthread.php?t=147060
	 */
	static function handler($errno, $errstr, $errfile, $errline, $errcontext) {
		$ret = null;
//	    if(!(error_reporting() & $errno)) 
//	        return; 
	    switch($errno) { 
	    case E_STRICT       : 
	    case E_NOTICE       :
	    	return;
	    case E_WARNING      : 
	    case E_USER_WARNING :  
	    case E_USER_NOTICE  : 
	        $type = 'warning'; 
	        $fatal = false; 
	        break; 
	    default             : 
	        $type = 'fatal error'; 
	        $fatal = true; 
	        break; 
	    } 
	    if(php_sapi_name() == 'cli') { 
	        $ret .= 'Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' <b>' . $errline . '</b>:' . "\n"; 
	        foreach(array_reverse(debug_backtrace()) as $item) 
	            $ret .= '  ' . (isset($item['file']) ? $item['file'] : '<unknown file>') . ' <b>' . (isset($item['line']) ? $item['line'] : '<unknown line>') . '</b> calling ' . $item['function'] . '()' . "\n"; 
	    } else {  
	        $ret .= '  Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' <b>' . $errline . '</b>:' . "\n"; 
	        $ret .= '  <ol>' . "\n"; 
	        foreach(array_reverse(debug_backtrace()) as $item) 
	            $ret .= '    <li>' . (isset($item['file']) ? $item['file'] : '<unknown file>') . ' <b>' . (isset($item['line']) ? $item['line'] : '<unknown line>') . '</b> calling ' . $item['function'] . '()</li>' . "\n"; 
	        $ret .= '  </ol>' . "\n";  
	    }
	    if($fatal) {
	    	error::fatal($ret); 
     		exit(1);
		} else {
			error::warning($ret);
		}
	}
	
	static function warning($msg) {
		html::messageBox($msg, "Warning", "ca5600");
		error::log(error::TYPE_WARNING, $msg);
	}
	
	static function fatal($msg) {
		html::messageBox($msg, "Error", "800000");
		error::log(error::TYPE_FATAL, $msg);
		die();
	}
	
	static function acl($msg) {
		html::messageBox($msg, "Access", "800000");
		//error::log(error::TYPE_ACL, $msg);
	}
	
	static function log($type, $msg) {
		$line = date(DATE_ISO8601)."; ".$type."; \"".addslashes(str_replace("\n", ";", $msg))."\"";
		$line .= "; \$_GET = ".str_replace("\n", "", var_export($_GET, true));
		$line .= "; \$_POST = ".str_replace("\n", "", var_export($_POST, true));
		$line .= "; \$_SESSION = ".str_replace("\n", "", var_export($_SESSION, true));
		$line .= "\r\n";
		$fp = fopen('logs/error.log', 'a');
		fwrite($fp, $line);
		fclose($fp);
	}
	
}
?>